package cn.ijero.dragdemo

import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.LocalOverScrollConfiguration
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.draggable
import androidx.compose.foundation.gestures.rememberDraggableState
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import cn.ijero.dragdemo.testdata.testData
import cn.ijero.dragdemo.ui.theme.DragDemoTheme
import kotlinx.coroutines.launch
import org.burnoutcrew.reorderable.*
import kotlin.math.abs
import kotlin.math.roundToInt

class MainActivity : ComponentActivity() {
    @ExperimentalFoundationApi
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            DragDemoTheme {
                // A surface container using the 'background' color from the theme
                Surface(color = MaterialTheme.colors.background) {
                    Greeting()
                }
            }
        }
    }
}

@ExperimentalFoundationApi
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun Greeting() {
    val reorderState = rememberReorderState()
    val testData = testData

    var swipedIndex by remember {
        mutableStateOf(-1)
    }

    CompositionLocalProvider(LocalOverScrollConfiguration provides null) {
        LazyColumn(
            state = reorderState.listState,
            modifier = Modifier
                .padding(24.dp)
                .fillMaxSize()
                .reorderable(
                    reorderState,
                    { fromPos, toPos -> testData.move(fromPos.index, toPos.index) }
                ),
        ) {
            itemsIndexed(testData) { index, item ->
                val swipeWidth = (-90).dp
                val swipeWidthPx = with(LocalDensity.current) { swipeWidth.toPx() }
                var offsetX by remember {
                    mutableStateOf(0f)
                }

                var isDragging by remember {
                    mutableStateOf(false)
                }

                val targetValue = if (isDragging) {
                    offsetX
                } else {
                    if (swipedIndex == index) {
                        swipeWidthPx
                    } else {
                        0f
                    }
                }

                val swipeAnimateState by animateFloatAsState(
                    targetValue = targetValue
                )

                val state = rememberDraggableState(onDelta = {
                    when {
                        offsetX + it < swipeWidthPx -> {
                            offsetX = swipeWidthPx
                        }
                        offsetX + it > 0f -> {
                            offsetX = 0f
                        }
                        else -> {
                            offsetX += it
                        }
                    }
                })

                ConstraintLayout(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(40.dp)
                        .draggedItem(reorderState.offsetByIndex(index))
                        .detectReorderAfterLongPress(reorderState)
                        .draggable(
                            state,
                            orientation = Orientation.Horizontal,
                            onDragStarted = {
                                swipedIndex = -1
                                isDragging = true
                            },
                            onDragStopped = {
                                if (offsetX < swipeWidthPx * 0.5f) {
                                    swipedIndex = index
                                }
                                isDragging = false
                            }
                        ),
                ) {
                    val (text1, text2) = createRefs()
                    Text(
                        modifier = Modifier
                            .background(Color.Red)
                            .padding(8.dp)
                            .constrainAs(text1) {
                                end.linkTo(parent.end)
                                centerVerticallyTo(parent)
                            }
                            .clickable {
                                testData.removeAt(index)
                                swipedIndex = -1
                            },
                        text = "删除",
                    )

                    Text(
                        modifier = Modifier
                            .offset {
                                IntOffset(swipeAnimateState.roundToInt(), 0)
                            }
                            .background(MaterialTheme.colors.background)
                            .padding(8.dp)
                            .fillMaxWidth()
                            .constrainAs(text2) {
                                centerVerticallyTo(parent)
                            },
                        text = item,
                        maxLines = 1
                    )
                }

            }
        }

    }
}

@ExperimentalFoundationApi
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    DragDemoTheme {
        Greeting()
    }
}